<?php
declare (strict_types=1);

namespace app\circle\logic\admin;

use app\admin\logic\system\Log;
use app\circle\model\admin\Circle as CircleModel;
use app\common\exception\LogicException;

/**
 * Class Circle
 *
 * @package app\circle\logic\admin
 */
class Circle extends CircleModel
{

    /**
     * 获取列表数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/17
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [])
    {
        return $this->with(['user'])->where($map)->order('create_time', 'desc')->append(['type_text'])->paginate($this->getListRows());
    }

    /**
     * 删除圈子
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/28
     *
     * @param string $ids
     */
    public function deleteCircles($ids)
    {
        $circles = $this->whereIn('id', (string)$ids)->selectOrFail();

        $circles->each(function ($item) {
            if (!$item->delete()) {
                throw new LogicException('删除失败');
            }
            Log::write('删除动态【' . $item->content . '】', 'circle', 'delete', true);
        });

    }

    /**
     * 设置推荐状态
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/15
     *
     * @param int $id
     * @param     $isRecommend
     */
    public function setRecommend(int $id, $isRecommend)
    {
        $circle            = $this->findOrFail($id);
        $circle->recommend = $isRecommend;

        if (!$circle->save()) {
            throw new LogicException('设置推荐失败');
        }
    }

    /**
     * 获取圈子基本信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/16
     *
     * @param int $id
     * @return Circle|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfoById(int $id)
    {
        return $this->with(['user'])->where('id', $id)->append(['type_text', 'attach_url'])->findOrFail();
    }
}